package com.xxwy.spring.event;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * {@link org.springframework.context.event.EventListener}.
 *
 * @author xxwy
 * @date 2021/9/16 0016
 */
@EnableAsync
public class AnnotationEventListenerDemo {

    /**
     * 事件监听器: 通过参数类型，控制事件处理
     * @param applicationEvent 事件
     */
    @EventListener
    @Async
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        System.out.println("线程："+ Thread.currentThread().getName()+ "收到事件 ： " + applicationEvent);
    }

    @Bean
    public Executor taskExecutor() {
        return Executors.newSingleThreadExecutor(new CustomizableThreadFactory("my-spring-event-thread-pool"));
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(AnnotationEventListenerDemo.class);
        // 启动
        context.refresh();

        context.publishEvent(new MySpringEvent("HELLO WORLD"));
        context.close();
    }
}
